<?php

/**
 * products actions.
 *
 * @package    corpon
 * @subpackage products
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class productsActions extends sfActions
{
  public function executeIndex(sfWebRequest $request)
  {
    $this->products = new Product();

    $this->pager = new sfDoctrinePager('Product',sfConfig::get('app_max_products'));
    $this->pager->setQuery($this->products->getProductsQuery());
    $this->pager->setPage($request->getParameter('page', 1));
    $this->pager->init();

    $this->products = $this->pager->getResults();
  }

  public function executeProductsAdmin(sfWebRequest $request)
  {
    $this->products = new Product();

    $this->pager = new sfDoctrinePager('Product',sfConfig::get('app_max_products'));
    $this->pager->setQuery($this->products->getProductsAdminQuery());
    $this->pager->setPage($request->getParameter('page', 1));
    $this->pager->init();

    $this->products = $this->pager->getResults();
  }

  public function executeHome(sfWebRequest $request)
  {
      
      $today = date('Y-m-d');
      $this->products = Doctrine::getTable('Product')
                ->createQuery('p')
                ->select('p.*')
                ->where('p.status = 1')
                ->andWhere('p.start_date <= ?',$today)
                ->andWhere('p.end_date >= ?',$today)
                ->orderBy('Rand()')
                ->limit('4')
                ->execute();
      
     $this->productHigthlight = Doctrine::getTable('Product')
                ->createQuery('p')
                ->select('p.*')
                ->where('p.status = 1')
                ->andWhere('p.start_date <= ?',$today)
                ->andWhere('p.end_date >= ?',$today)
                ->orderBy('Rand()')
                ->limit('1')
                ->execute();
     
     $this->priceHigthlight = explode(".", $this->productHigthlight[0]->getPrice());
      
      //$this->products=$productss->getProductsQueryAllRandom();
      

  }

  public function executeShow(sfWebRequest $request)
  {
      $this->product = Doctrine_Core::getTable('Product')->find(array($request->getParameter('id_product')));
      $this->forward404Unless($this->product);
      
      $today = date('Y-m-d');
      $this->products = Doctrine::getTable('Product')
                ->createQuery('p')
                ->select('p.*')
                ->where('p.status = 1')
                ->andWhere('p.start_date <= ?',$today)
                ->andWhere('p.end_date >= ?',$today)
                ->orderBy('Rand()')
                ->limit('4');

    if ($request->getParameter('companyNameUrl')) :
     $account = Doctrine_Core::getTable('Account')->findOneByCompanyNameUrl(array($request->getParameter('companyNameUrl')));
     $this->forward404Unless($account);
     $this->products->andWhere('p.id_account = ?',$account->getIdAccount());
    endif;

    $this->products = $this->products->execute();
  }

  public function executeNew(sfWebRequest $request)
  {
    $this->form = new ProductForm();
                $today = date('Y-m-d');
      $this->products = Doctrine::getTable('Product')
                ->createQuery('p')
                ->select('p.*')
                ->where('p.status = 1')
                ->andWhere('p.start_date <= ?',$today)
                ->andWhere('p.end_date >= ?',$today)
                ->orderBy('Rand()')
                ->limit('4')
                ->execute();
  }

  public function executeCreate(sfWebRequest $request)
  {
    $this->forward404Unless($request->isMethod(sfRequest::POST));

    $this->form = new ProductForm();

    $this->processForm($request, $this->form);

    $this->setTemplate('new');
  }

  public function executeEdit(sfWebRequest $request)
  {
    $this->forward404Unless($product = Doctrine_Core::getTable('Product')->find(array($request->getParameter('id_product'))), sprintf('Object product does not exist (%s).', $request->getParameter('id_product')));
    $this->form = new ProductForm($product);
  }

  public function executeUpdate(sfWebRequest $request)
  {
    $this->forward404Unless($request->isMethod(sfRequest::POST) || $request->isMethod(sfRequest::PUT));
    $this->forward404Unless($product = Doctrine_Core::getTable('Product')->find(array($request->getParameter('id_product'))), sprintf('Object product does not exist (%s).', $request->getParameter('id_product')));
    $this->form = new ProductForm($product);

    $this->processForm($request, $this->form);

    $this->setTemplate('edit');
  }

  public function executeShoppingCart(sfWebRequest $request)
  {
    $cart_req = $this->getUser()->getAttribute('cart');

    //$this->shipping_amount = Doctrine_Core::getTable('ShippingAmount')->find(array(1));

    if(isset($cart_req)) :
        $this->cart = $this->getUser()->getAttribute('cart');
    else :
        $this->cart = false;
    endif;

  }

  public function executeAddToCart(sfWebRequest $request)
  {
    $product_name = $request->getParameter('product_name');
    $product_description = $request->getParameter('product_description');
    $product_price = $request->getParameter('product_price');
    $id_product = $request->getParameter('id_product');
    $shipping_price = $request->getParameter('shipping_price');
    $company = $request->getParameter('company');

    $quantity_req = $request->getParameter('product_quantity');
    
    $product_instance = Doctrine_Core::getTable('Product')->find(array($id_product));

    if(empty($quantity_req)) :
      $quantity = $product_instance->getIncrement();
    else :
      if ($request->getParameter('product_quantity')%$product_instance->getIncrement()!=0) :
          $quantity= $product_instance->getIncrement();
      else :
          $quantity= $request->getParameter('product_quantity');
      endif;
    endif;

    $cart_req = $this->getUser()->getAttribute('cart');
    
    if(isset($cart_req)) $cart = $this->getUser()->getAttribute('cart');
	
    $cart[md5($id_product)] = array('id' => md5($id_product),
                                  'quantity' => $quantity,
                                  'product_name' => $product_name,
                                  'product_description' => $product_description,
                                  'product_price' => $product_price,
                                  'id_product' => $id_product,
                                  'shipping_price' => $shipping_price);

    $this->getUser()->setAttribute('cart', $cart);

    if ($request->getParameter('company')) :
       $this->redirect('/shoppingCart/'.$company);
    else :
       $this->redirect('products/shoppingCart');
    endif;

  }

  public function executeRemoveFromCart(sfWebRequest $request)
  {

    $cart = $this->getUser()->getAttribute('cart');

    $id = $request->getParameter('id_product');

    unset($cart[$id]);
    
    $this->getUser()->setAttribute('cart', $cart);

    if ($request->getParameter('company')=="") :
        $this->redirect('products/shoppingCart');
    else :
        $this->redirect('shoppingCart/'.$request->getParameter('company'));
    endif;
  }

  public function executeDelete(sfWebRequest $request)
  {
    $request->checkCSRFProtection();

    $this->forward404Unless($product = Doctrine_Core::getTable('Product')->find(array($request->getParameter('id_product'))), sprintf('Object product does not exist (%s).', $request->getParameter('id_product')));
    $product->delete();

    $this->redirect('products/index');
  }

  protected function processForm(sfWebRequest $request, sfForm $form)
  {
    $form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
    if ($form->isValid())
    {
      $product = $form->save();

      for ($i = 1; $i <= 3; $i++) :

	switch ($i) :
          case 1:
            $filename = $product->getPhoto1();
            break;
          case 2:
            $filename = $product->getPhoto2();
            break;
	  case 3:
            $filename = $product->getPhoto3();
            break;
	endswitch;

	if ($filename!="")
    	{
	  // IMAGEN GRANDE
	  $img = new sfImage(sfConfig::get('sf_upload_dir').'/products/'.$filename);
	  $response = $this->getResponse();
	  $response->setContentType($img->getMIMEType());

	  $width = $img->getWidth();
	  $height = $img->getHeight();
	  $new_width = $width;
	  $new_height = $height;
	  while ($new_width >= 486 or $new_height >= 369)
	  {
            $new_width = $new_width * 99/100;
            $new_height = $new_height * 99/100;
	  }

	  $img->resize($new_width,$new_height);
	  $img->saveAs(sfConfig::get('sf_upload_dir').'/products/'.$filename);

	  // IMAGEN FICHA
	  $img_ficha = new sfImage(sfConfig::get('sf_upload_dir').'/products/'.$filename);
	  $response = $this->getResponse();
	  $response->setContentType($img_ficha->getMIMEType());

	  $width = $img_ficha->getWidth();
	  $height = $img_ficha->getHeight();
	  $new_width = $width;
	  $new_height = $height;
	  //while ($new_width >= 193 or $new_height >= 144)
          while ($new_width >= 284 or $new_height >= 282)
	  {
            $new_width = $new_width * 99/100;
            $new_height = $new_height * 99/100;
	  }

	  $img_ficha->resize($new_width,$new_height);
	  $img_ficha->saveAs(sfConfig::get('sf_upload_dir').'/products/preview/'.$filename);

	  // IMAGEN LISTADO
	  $img_listado = new sfImage(sfConfig::get('sf_upload_dir').'/products/'.$filename);

	  $response = $this->getResponse();
	  $response->setContentType($img_listado->getMIMEType());

	  $width = $img_listado->getWidth();
	  $height = $img_listado->getHeight();
	  $new_width = $width;
	  $new_height = $height;
	  while ($new_width >= 142 or $new_height >= 141)
	  {
            $new_width = $new_width * 99/100;
            $new_height = $new_height * 99/100;
	  }

	  $img_listado->resize($new_width,$new_height);
	  $img_listado->saveAs(sfConfig::get('sf_upload_dir').'/products/list/'.$filename);

	  // IMAGEN THUMB
	  $img_thumb = new sfImage(sfConfig::get('sf_upload_dir').'/products/'.$filename);

	  $response = $this->getResponse();
	  $response->setContentType($img_thumb->getMIMEType());

	  $width = $img_thumb->getWidth();
	  $height = $img_thumb->getHeight();
	  $new_width = $width;
	  $new_height = $height;
	  while ($new_width >= 72 or $new_height >= 68)
	  {
            $new_width = $new_width * 99/100;
            $new_height = $new_height * 99/100;
	  }

	  $img_thumb->resize($new_width,$new_height);
	  $img_thumb->saveAs(sfConfig::get('sf_upload_dir').'/products/thumb/'.$filename);
	}
      endfor;

      $this->redirect('product_show',$product);
    }
  }
}
